package com.hmdp.common.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.common.utils.RedisConstants;
import com.hmdp.common.utils.UserHolder;
import com.hmdp.dto.UserDto;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.common.utils.RedisConstants.LOGIN_TOKEN_KEY;

/**
 * @author WDs , wds8.24@outlook.com
 * @version 1.0
 * @since 2023-01-09 20:30
 * token刷新拦截器
 * 存储当前登录用户的用户信息，刷新token有效期
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate redisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) {
            return true;//no token
        }
        Map<Object, Object> map = redisTemplate.opsForHash().entries(LOGIN_TOKEN_KEY + token);
        if (map.isEmpty()) {
            return true;//no user
        }

        UserDto currentUser = BeanUtil.fillBeanWithMap(map, new UserDto(), false);
        UserHolder.saveUser(currentUser);
        // refresh token time left
        redisTemplate.expire(LOGIN_TOKEN_KEY + token, RedisConstants.LOGIN_TOKEN_TTL, TimeUnit.MINUTES);
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserHolder.removeUser();
    }
}
